<?php
/**
 * @author spenceryg
 * @date 2022/11/24
 * @time 10:07 下午
 * @focus love & life
 */

namespace app\admin\controller\sys\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Model;
use think\model\relation\BelongsToMany;

class AdminUserModel extends Model
{
    use \app\common\traits\model\ModelTreeTrait;


    protected $name = 'admin_user';
    protected $table = 'db_admin_user';

    /**
     * pid获取器
     * @param $value
     * @return mixed|string
     */
    public function getPidAttr($value)
    {
        return $value == 0 ? '顶级' : $this->where('pid', $value)->value('username');
    }



    /**
     * 关联模型 adminRole
     * @return BelongsToMany
     */
    public function adminRole(): BelongsToMany
    {
        return $this->belongsToMany(AdminRoleModel::class, 'admin_role_user', 'admin_role_id', 'admin_user_id');
    }

    /**
     * 上次登录时间获取器
     * @param $value
     * @return false|string
     */
    public function getLastLoginTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '未登录过';
    }

    /**
     * 根据用户名获取用户信息
     * @param $username
     * @return mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDataByUserName($username)
    {
        if (!$username) {
            return [];
        }
        return $this->where('username', $username)->find();
    }

    /**
     * 更新登录用户信息
     * @param $id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateUserInfo($id)
    {
        $user = $this->find($id);
        if ($user) {
            $user->last_login_time = time();
            $user->last_login_ip = request()->ip();
            $user->save();
        }
    }
}
